package com.supinfo.suptracking.servlet;

import com.supinfo.suptracking.entity.Zone;
import com.supinfo.suptracking.service.ZoneService;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Fabien, Jérémy, Ludovic, Brice
 */

@WebServlet(name = "AddZoneServlet", urlPatterns = {"/auth/addZone"})
public class AddZoneServlet extends HttpServlet {

    @EJB
    private ZoneService zoneServ;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.sendRedirect(getServletContext().getContextPath()+ "/jsp/auth/addZone.jsp");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Zone zone = new Zone();

        String name = request.getParameter("name");
        String latitude = request.getParameter("latitude");
        String longitude = request.getParameter("longitude");
        String radiusMeter = request.getParameter("radiusMeter");
        
        Date lowTimeStamp = null;
        
        String lowTimeStampTemp = request.getParameter("lowTimeStamp");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            lowTimeStamp = sdf.parse(lowTimeStampTemp);
        } catch (ParseException ex) {
            Logger.getLogger(ZonesServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        Date highTimeStamp = null;
        String highTimeStampTemp = request.getParameter("highTimeStamp");
        SimpleDateFormat sdfF = new SimpleDateFormat("yyyy-MM-dd");
        try {
            highTimeStamp = sdf.parse(highTimeStampTemp);
        } catch (ParseException ex) {
            Logger.getLogger(ZonesServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        zone.setName(name);
        zone.setLatitude(latitude);
        zone.setLongitude(longitude);
        zone.setRadiusMeter(radiusMeter);
        zone.setHighTimestamp(highTimeStamp);
        zone.setLowTimeStamp(lowTimeStamp);
        
        zoneServ.processAddZone(zone);

        response.sendRedirect(getServletContext().getContextPath()+ "/auth/zones");
    }
}
